package com.linsen.erp.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linsen.erp.admin.service.IRoleMenuService;
import com.linsen.erp.admin.entity.RoleMenuEntity;
import com.linsen.erp.admin.mapper.RoleMenuMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色-菜单关联关系 服务实现类
 * </p>
 *
 * @author zhaoyong
 * @since 2023-07-24
 */
@Service
@RequiredArgsConstructor
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenuEntity> implements IRoleMenuService {

    @Override
    public List<String> getMenuIdByRoleId(String roleId) {
        return this.list(
                new LambdaQueryWrapper<RoleMenuEntity>()
                        .eq(RoleMenuEntity::getRoleId,roleId)
        ).stream().map(RoleMenuEntity::getMenuId).collect(Collectors.toList());
    }

    @Transactional
    @Override
    public void set(String roleId, List<String> menuIdList) {
        //清除原有设置
        this.remove(
                new LambdaQueryWrapper<RoleMenuEntity>()
                        .eq(RoleMenuEntity::getRoleId,roleId)
        );

        if (ObjectUtil.isNotEmpty(menuIdList)){
            List<RoleMenuEntity> roleMenuEntityList = menuIdList.stream().map(menuId -> {
                RoleMenuEntity roleMenuEntity = new RoleMenuEntity();
                roleMenuEntity.setRoleId(roleId);
                roleMenuEntity.setMenuId(menuId);
                return roleMenuEntity;
            }).collect(Collectors.toList());

            this.saveBatch(roleMenuEntityList);
        }
    }
}
